'''
Created on Oct 13, 2012

@author: raygomez
'''

from AVP import AVP
from Error import InvalidAVPLengthError
import struct

class Unsigned32AVP(AVP):
    
    def __init__(self, code, value, vendorId=0):
        AVP.__init__(self, code, struct.pack("!I", value), vendorId)
        
    def getValue(self):
        """Returns the payload as a 32-bit unsigned value."""
        return struct.unpack("!I", self.payload)[0]
    
    def setValue(self, value):
        """Sets the payload to a 32-bit unsigned value."""
        self.payload = struct.pack("!I", value)
        
    def __str__(self):
        return str(self.code) + ":" + str(self.getValue())
    
    @staticmethod
    def convert(avp):
        """Convert generic AVP to an Unsigned32AVP
        Raises: InvalidAVPLengthError
        """
        if len(avp.payload) != 4:
            raise InvalidAVPLengthError(avp)
        value = struct.unpack("!I", avp.payload)[0]
        a = Unsigned32AVP(avp.code, value, avp.vendorId)
        a.flags = avp.flags
        return a